$(function() {

$.input = {};

$.input.srcElements = null;

$.input.start = function()
{
	$.input.srcElements = $.input.createElements();

	$.input.monitorChanges();
}

$.input.monitorChanges = function()
{
	setInterval(function() 
	{
		$("input.searchInput").each(function(i, p)
		{
			var txt = p;

			var last_value = txt.getAttribute("last_value");

			if(last_value == txt.value)
				return;

			var contains = txt.value.indexOf(last_value) > -1;

			txt.setAttribute("last_value", txt.value);

			if(txt.getAttribute("preventTriggers") == true)
				return;

			var resultId = txt.getAttribute("results");

			var results = document.getElementById(resultId);

			if(!contains)
			{
				results.innerHTML = "";
				results.setAttribute("hits", 0);
			}

//			if(results.parentNode.id != "wrap")
//				results.style.display = "none";

			if(txt.value.length > 0 || resultId)
			{
				txt.context.start(txt.value);
			}
		})


	}, 100);
}

$.input.onKeyPress = function(e)
{
	if (e.keyCode != 13)
		return;

	var parent = $(e.target.parentNode);

	var input = $("input", parent);

	var t = $(e.target);

	var address = t.attr("address");

	var value = t.val();

	if(address)
	  value = address.replace(/\+/g, "%2B").replace(/#/g, "%23").replace(/\?/g, "%3f");

	$.input.post(value, t.parents("div[address]").attr("address"), function(e)
	{
		if($.user.userAddress)
			$.input.post($.user.userAddress, e)
	});

	e.target.context.start(e.target.value);
}


$.input.appendInput = function($target, resultsId)
{
	$target.after($("<div />",
	{
		class : "innerButton searchButton",
	}));

	$target.
		attr("results", resultsId).
		attr("last_value", "").
		addClass("searchInput").
		keypress($.input.onKeyPress).
		focus($.input.onFocus).
		blur($.input.onBlur);	

	$.context.create($target);

	return $target;
}

$.input.onFocus = function(e)
{
	
}

$.input.onBlur = function(e)
{
	
}

$.input.createElements = function()
{
	var result = document.createElement("div");

	result.setAttribute("class", "input");


	var input = document.createElement("input");

	input.setAttribute("last_value", "");
	

	input.setAttribute("class", "searchInput");

	result.appendChild(input);	


	var button = document.createElement("div");

	button.setAttribute("class", "innerButton searchButton");	

	result.appendChild(button);	


	var userSelectDiv = document.createElement("div");

	userSelectDiv.className = "results";

	result.appendChild(userSelectDiv);		



/*
	var button2 = document.createElement("input");

	button2.setAttribute("class", "innerButton searchButton");	

	result.appendChild(button2);	
*/

	return result;
}

})